/**
 * Copyright (C) 2011 - @le.nguyen
 * @Created Jul 26, 2011
 *
 * TODO
 */
package com.conan.app.dailyflickr.activity;

import android.app.Activity;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.conan.app.dailyflickr.App;
import com.conan.app.dailyflickr.app.ApplicationUtils;
import com.conan.app.dailyflickr.app.ProgressNotification;
import com.conan.app.dailyflickr.provider.ProviderUtils;
import com.conan.app.dailyflickr.provider.ProviderUtils.DailyInfo;
import com.conan.app.flickrdaily.R;

/**  */
public class DailyImageDialog extends Activity implements OnClickListener{
    boolean mIsWallpaper = false;
    TextView txDowload, txWallpaper, txPhotos, txtShare;
    int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    public static final String PREFS_NAME_SET_WALLPAPER = "set_wallpaper";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.flickr_action);
        
        findViewById(R.id.tbrow_download).setOnClickListener(this);
        findViewById(R.id.tbrow_wallpaper).setOnClickListener(this);
        findViewById(R.id.tbrow_photos).setOnClickListener(this);
        findViewById(R.id.tbrow_share).setOnClickListener(this);
        
        Intent intent = getIntent();
        if(intent != null) {
            appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
            mIsWallpaper = intent.getBooleanExtra(PREFS_NAME_SET_WALLPAPER, false);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.tbrow_download:
            startDownloadImage(false);
            break;

        case R.id.tbrow_wallpaper:
            startDownloadImage(true);
            break;

        case R.id.tbrow_photos:
            Intent intent = new Intent(getApplicationContext(), DowloadedPhotosActivity.class);
            startActivity(intent);
            finish();
            break;
        case R.id.tbrow_share:
            DailyInfo info = ProviderUtils.getWidgetInfoFromProvider(getApplicationContext(),  appWidgetId);
            String url = info._url.replaceAll("_m.jpg", "_b.jpg");
            
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
             shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_subject));
            shareIntent.putExtra(Intent.EXTRA_TEXT, info._title + " " + url);
            startActivity(Intent.createChooser(shareIntent, getString(R.string.share_title)));
            finish();
            break;
        default:
            break;
        }

    }

    private void startDownloadImage(final boolean isWallpaper){		
        Intent intent = new Intent(this, DownloadService.class);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        intent.putExtra(PREFS_NAME_SET_WALLPAPER, isWallpaper);
        startService(intent);
        
        finish();
    }

    private void startDownload(final boolean isWallpaper){
        Thread thread = new Thread() {
            @Override
            public void run() {
                DailyInfo info = ProviderUtils.getWidgetInfoFromProvider(getApplicationContext(), appWidgetId);

                // Log.e(DailyPhotoData.TAG, "DailyImageDiaglog -> Dowload... !! " + info._url);
                if(!TextUtils.isEmpty(info._url)){
                    // String url = info._url.replaceAll("_m.jpg", "_b.jpg");
                    boolean rs = ApplicationUtils.downloadBitmap(getApplicationContext(), 
                            info._url, info._title, isWallpaper);
                    // mHandler.sendEmptyMessage(rs ? 0 : 1);
                    finish();
                }
            }
        };
        thread.start();
    }


    public static class DownloadService extends Service{
        int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
        ProgressNotification notifications;
        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }

        @Override
        public void onStart(Intent intent, int startId) {			
            super.onStart(intent, startId);
            notifications = ProgressNotification.getInstance(this);

            ConnectivityManager connMan = (ConnectivityManager) this
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            if(connMan.getActiveNetworkInfo() != null 
                    && !(connMan.getActiveNetworkInfo().isConnected() ) ){
                App.makeToastMessage("Internet disconnected !!! ");
                return;
            }


            boolean isWallpaper = false;
            if(intent != null){
                isWallpaper = intent.getBooleanExtra(PREFS_NAME_SET_WALLPAPER, false);
                mAppWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
            }

            DailyInfo info = ProviderUtils.getWidgetInfoFromProvider(getApplicationContext(),  mAppWidgetId);
            startDownload(isWallpaper, info._url, info._title);
        }

        private void startDownload(final boolean isWallpaper,final String url, final String title){
            Thread thread = new Thread() {
                @Override
                public void run() {					
                    // Log.e(DailyPhotoData.TAG, "DailyImageDiaglog -> Dowload... !! " + url);
                    if(!TextUtils.isEmpty(url)){
                        notifications.showNotification(url, title, isWallpaper);
                        boolean rs = ApplicationUtils.downloadBitmap(getApplicationContext(), 
                                url, title, isWallpaper);
                        Message message = mHandler.obtainMessage(rs ? DOWNLOAD_SUCCESS : DOWNLOAD_FAILED, url);						
                        mHandler.sendMessage(message);
                        // Message message = mHandler.obtainMessage( DOWNLOAD_SUCCESS, url);
                        // mHandler.sendMessageDelayed(message, 1000);
                    }
                }
            };
            thread.start();
        }

        private final int KILL_SERVICE = 100;
        private final int DOWNLOAD_FAILED = 101;
        private final int DOWNLOAD_SUCCESS = 102;
        private final int DOWNLOAD_UPDATE_PROGRESS = 103;
        private Handler mHandler = new  Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                case DOWNLOAD_SUCCESS:
                    App.makeToastMessage("Dowload finished !!! ");
                    // updateWidgetStatus(mAppWidgetId, "Dowload finished !!!");
                    notifications.updateNotificationDone((String)msg.obj, true);
                    mHandler.sendEmptyMessageDelayed(KILL_SERVICE, 1250);
                    break;
                case DOWNLOAD_FAILED:
                    App.makeToastMessage("Dowload falied !!! ");
                    // updateWidgetStatus(mAppWidgetId, "Dowload falied !!! ");
                    notifications.updateNotificationDone((String)msg.obj, false);
                    mHandler.sendEmptyMessageDelayed(KILL_SERVICE, 1250);
                    break;	
                case KILL_SERVICE:
                    // stop service
                    if(!notifications.hasDownloading()){
                        stopSelf();
                    }
                    break;	
                case DOWNLOAD_UPDATE_PROGRESS:

                    break;		
                default:
                    break;
                }
            }
        };


        private void updateWidgetStatus(int widgetId, String title){
            RemoteViews updateViews = new RemoteViews(getApplicationContext()
                    .getPackageName(),  R.layout.flickr_widget);
            AppWidgetManager manager = AppWidgetManager.getInstance(DownloadService.this);


            updateViews.setTextViewText(R.id.tv_main_message_text_id, title);
            manager.updateAppWidget(widgetId, updateViews);
        }

        /* (non-Javadoc)
         * @see android.app.Service#onDestroy()
         */
        @Override
        public void onDestroy() {
            // update all Notification to failed

            super.onDestroy();
        }
    }

}
